package com.sitech.portal.webHooks;

import com.sitech.ibnms.core.BaseIbnmsAction;
import com.sitech.ibnms.util.JSONUtil;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_USER_ROLE;
import com.sitech.portal.system.form.UserForm;
import com.sitech.portal.webHooks.domain.HookRequestBody;
import com.sitech.portal.webHooks.domain.WebHooks;
import com.sitech.portal.system.service.ISysLogInmsgService;
import com.sitech.portal.system.service.ISysRoleService;
import com.sitech.portal.webHooks.domain.User;
import com.sitech.portal.webHooks.service.IWebHooksService;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: yanran
 * Date: 15-9-11
 * Time: 上午10:19
 * To change this template use File | Settings | File Templates.
 */
public class UserEventProcessor extends BaseIbnmsAction {
    private ISysLogInmsgService sysLogInmsgService;
    private IWebHooksService webHooksService;
    private ISysRoleService sysRoleService;
    private static final Log logger = LogFactory.getLog(UserEventProcessor.class);
    private String testUrl;
    private String tip;

    public Object whenAddUser(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        TblSYS_LOGINMSG after = (TblSYS_LOGINMSG)joinPoint.getArgs()[0];
        User userBefore =  null;
        User userAfter =  new User(after);
        userAfter.setCREATED_BY(this.getCurrentUser().getLOGIN_ID());
        userAfter.setCREATED_AT(EventProcessorUtil.getNowTime());
        String object_id = after.getLOGIN_ID();
        String object_kind = "user";
        String operate_kind = "create";
        Object o = null;
        try {
            o = joinPoint.proceed();
            //调用接口
            List<WebHooks>  list= webHooksService.selectWebHooksUrl(object_kind);
            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);
            for(WebHooks os : list){
                String url = os.getURL();
                PostMethod post = new PostMethod(url);
                 post.setRequestBody(JSONUtil.toJSON(hrb));
                try {
                    new HttpClient().executeMethod(post);
                }catch (Exception e){
                    logger.error(e);
                }
                logger.info("增加用户同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }
    public Object whenUpdateUser(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        TblSYS_LOGINMSG after = (TblSYS_LOGINMSG)joinPoint.getArgs()[0];
        TblSYS_LOGINMSG before = sysLogInmsgService.findUserRoleByPk(after.getLOGIN_ID());
        String object_id = after.getLOGIN_ID();
        String object_kind = "user";
        String operate_kind = "update";

        User userBefore =  new User(before);
        User userAfter =  new User(after);

        userAfter.setUPDATED_BY(this.getCurrentUser().getLOGIN_ID());
        userAfter.setUPDATED_AT(EventProcessorUtil.getNowTime());

        Object o = null;
        try {
            o = joinPoint.proceed();
            //调用接口
            List<WebHooks>  list= webHooksService.selectWebHooksUrl(object_kind);
            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);

            for(WebHooks os : list){
                String url = os.getURL();
                PostMethod post = new PostMethod(url);
                post.setRequestBody(JSONUtil.toJSON(hrb));
                try {
                    new HttpClient().executeMethod(post);
                }catch (Exception e){
                    logger.error(e);
                }
                logger.info("修改用户同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    public Object whenUpdateUserInHome(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String userId = (String)joinPoint.getArgs()[0];
        UserForm userForm = (UserForm)joinPoint.getArgs()[1];

        TblSYS_LOGINMSG before = sysLogInmsgService.findUserRoleByPk(userId);
        String object_id = userId;
        String object_kind = "user";
        String operate_kind = "update";

        User userBefore = new User();
        userBefore.setLOGIN_ID(userId);
        userBefore.setLOGIN_PHONE(before.getLOGIN_PHONE());
        userBefore.setLOCAL_PHONE(before.getLOCAL_PHONE());
        userBefore.setEMAIL_ADDR(before.getEMAIL_ADDR());

        User userAfter = new User();
        userAfter.setLOGIN_ID(userId);
        userAfter.setLOGIN_PHONE(userForm.getTelphone());
        userAfter.setLOCAL_PHONE(userForm.getLocal_phone());
        userAfter.setEMAIL_ADDR(userForm.getEmail());
        userAfter.setUPDATED_BY(this.getCurrentUser().getLOGIN_ID());
        userAfter.setUPDATED_AT(EventProcessorUtil.getNowTime());

        Object o = null;
        try {
            o = joinPoint.proceed();
            //调用接口
            List<WebHooks>  list= webHooksService.selectWebHooksUrl(object_kind);
            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);
            for(WebHooks os : list){
                String url = os.getURL();
                PostMethod post = new PostMethod(url);
                 post.setRequestBody(JSONUtil.toJSON(hrb));
                try {
                    new HttpClient().executeMethod(post);
                }catch (Exception e){
                    logger.error(e);
                }
                logger.info("修改用户电话同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    public Object whenDeleteUser(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String[]  delUsers= ( String[])joinPoint.getArgs()[0];
        ArrayList<TblSYS_LOGINMSG> userList = new ArrayList();
        for(String userid : delUsers){
            userList.add(sysLogInmsgService.findUserRoleByPk(userid));
        }
        Object o = null;
        try {
            o = joinPoint.proceed();
            String object_kind = "user";
            String operate_kind = "delete";
            List<WebHooks>  urllist= webHooksService.selectWebHooksUrl(object_kind);
            for(TblSYS_LOGINMSG user : userList){

                String object_id = user.getLOGIN_ID();
                TblSYS_LOGINMSG before = sysLogInmsgService.findUserRoleByPk(object_id);

                User userBefore =  new User(before);
                User userAfter =  new User();
                userAfter.setLOGIN_ID(object_id);
                userAfter.setDELETED_BY(this.getCurrentUser().getLOGIN_ID());
                userAfter.setDELETED_AT(EventProcessorUtil.getNowTime());

                HookRequestBody hrb = new HookRequestBody();
                hrb.setObject_kind(object_kind);
                hrb.setOperate_kind(operate_kind);
                hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
                hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
                hrb.setObject_id(object_id);
                    for(WebHooks os : urllist){
                        String url = os.getURL();
                        PostMethod post = new PostMethod(url);
                         post.setRequestBody(JSONUtil.toJSON(hrb));
                        try {
                            new HttpClient().executeMethod(post);
                        }catch (Exception e){
                            logger.error(e);
                        }
                        logger.info("删除用户同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
                    }
            }

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    public Object whenAddUserRole(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        String[]  afterRoles= ( String[])joinPoint.getArgs()[1];
        TblSYS_LOGINMSG lgmsg = (TblSYS_LOGINMSG)joinPoint.getArgs()[2];

        String object_id = lgmsg.getLOGIN_ID();
        String object_kind = "user";
        String operate_kind = "update";

        //取得原角色
        TblSYS_USER_ROLE rol = new TblSYS_USER_ROLE();
        rol.setLOGIN_ID(lgmsg.getLOGIN_ID());
        List<Map> beforeRoles = sysRoleService.findForRoleListByLonginId(rol);
        ArrayList beforelist = new ArrayList();
        for(Map m : beforeRoles){
            beforelist.add(m.get("ROLE_ID"));
        }

        User userBefore = new User();
        userBefore.setROLES(beforelist);
        userBefore.setLOGIN_ID(object_id);

        User userAfter = new User();
        userAfter.setROLES(Arrays.asList(afterRoles));
        userAfter.setLOGIN_ID(object_id);
        userAfter.setUPDATED_BY(this.getCurrentUser().getLOGIN_ID());
        userAfter.setUPDATED_AT(EventProcessorUtil.getNowTime());

        Object o = null;

        try {
            o = joinPoint.proceed();
            //调用接口
            List<WebHooks>  list= webHooksService.selectWebHooksUrl(object_kind);
            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);
            for(WebHooks os : list){
                String url = os.getURL();
                PostMethod post = new PostMethod(url);
                 post.setRequestBody(JSONUtil.toJSON(hrb));
                try {
                    new HttpClient().executeMethod(post);
                }catch (Exception e){
                    logger.error(e);
                }
                logger.info("修改用户角色同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }
    public Object whenDeleteUserRole(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String[]  delUsers = ( String[])joinPoint.getArgs()[0];
        Object o = null;
        try {
            o = joinPoint.proceed();
            String object_kind = "user";
            String operate_kind = "update";
            List<WebHooks>  urllist= webHooksService.selectWebHooksUrl(object_kind);
            for(String userid : delUsers){
                String object_id = userid;

                User userBefore = new User();
                userBefore.setROLES(null);
                userBefore.setLOGIN_ID(object_id);

                User userAfter = new User();
                userAfter.setROLES(new ArrayList());
                userAfter.setLOGIN_ID(object_id);
                userAfter.setUPDATED_BY(this.getCurrentUser().getLOGIN_ID());
                userAfter.setUPDATED_AT(EventProcessorUtil.getNowTime());

                HookRequestBody hrb = new HookRequestBody();
                hrb.setObject_kind(object_kind);
                hrb.setOperate_kind(operate_kind);
                hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
                hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
                hrb.setObject_id(object_id);
                for(WebHooks os : urllist){
                    String url = os.getURL();
                    PostMethod post = new PostMethod(url);
                     post.setRequestBody(JSONUtil.toJSON(hrb));
                    try {
                        new HttpClient().executeMethod(post);
                    }catch (Exception e){
                        logger.error(e);
                    }
                    logger.info("删除用户角色同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
                }
            }

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    public Object whenAddUserWorkGroup(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String  userId = ( String)joinPoint.getArgs()[0];
        String[]  wgIds = null;
        String  wgId = null;

        if(joinPoint.getArgs()[1] instanceof String[]){
              wgIds = ( String[])(joinPoint.getArgs()[1]);
        }else{
              wgId = ( String)joinPoint.getArgs()[1];
        }

        TblSYS_LOGINMSG lg =  sysLogInmsgService.findUserRoleByPk(userId) ;
        List beforeList = lg.getWorkGroups();

        List workgroupIds = new ArrayList();
        for(int i=0;i<beforeList.size();i++){
            HashMap workgroup = (HashMap)beforeList.get(i);
            workgroupIds.add(workgroup.get("WORKGROUP_ID"));
        }

        Object o = null;
        String object_id = userId;
        String object_kind = "user";
        String operate_kind = "update";
        try {
            o = joinPoint.proceed();
            List<WebHooks>  urllist= webHooksService.selectWebHooksUrl(object_kind);
            User userBefore = new User();
            userBefore.setWORKGROUPS(new ArrayList(workgroupIds));
            userBefore.setLOGIN_ID(object_id);

            workgroupIds.addAll(wgIds==null?Arrays.asList(new String[]{wgId}):Arrays.asList(wgIds));

            User userAfter = new User();
            userAfter.setWORKGROUPS(workgroupIds);
            userAfter.setLOGIN_ID(object_id);
            userAfter.setUPDATED_BY(this.getCurrentUser().getLOGIN_ID());
            userAfter.setUPDATED_AT(EventProcessorUtil.getNowTime());

            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);
            for(WebHooks os : urllist){
                String url = os.getURL();
                PostMethod post = new PostMethod(url);
                post.setRequestBody(JSONUtil.toJSON(hrb));
                try {
                    new HttpClient().executeMethod(post);
                }catch (Exception e){
                    logger.error(e);
                }
                logger.info("增加用户工作组同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
            }

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }
    public Object whenDeleteUserWorkGroup(ProceedingJoinPoint joinPoint) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String  userId = ( String)joinPoint.getArgs()[0];
        String  wgId = ( String)joinPoint.getArgs()[1];
        TblSYS_LOGINMSG lg =  sysLogInmsgService.findUserRoleByPk(userId) ;
        List beforeList = lg.getWorkGroups();

        List workgroupIds = new ArrayList();
        for(int i=0;i<beforeList.size();i++){
            HashMap workgroup = (HashMap)beforeList.get(i);
            workgroupIds.add(workgroup.get("WORKGROUP_ID"));
        }

        Object o = null;
        String object_id = userId;
        String object_kind = "user";
        String operate_kind = "update";
        try {
            o = joinPoint.proceed();
            List<WebHooks>  urllist= webHooksService.selectWebHooksUrl(object_kind);
            User userBefore = new User();
            userBefore.setWORKGROUPS(new ArrayList(workgroupIds));
            userBefore.setLOGIN_ID(object_id);

            workgroupIds.remove(wgId);

            User userAfter = new User();
            userAfter.setWORKGROUPS(workgroupIds);
            userAfter.setLOGIN_ID(object_id);
            userAfter.setUPDATED_BY(this.getCurrentUser().getLOGIN_ID());
            userAfter.setUPDATED_AT(EventProcessorUtil.getNowTime());

            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);
            for(WebHooks os : urllist){
                String url = os.getURL();
                PostMethod post = new PostMethod(url);
                post.setRequestBody(JSONUtil.toJSON(hrb));
                try {
                    new HttpClient().executeMethod(post);
                }catch (Exception e){
                    logger.error(e);
                }
                logger.info("删除用户工作组同步接口:"+url+"   status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString());
            }

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    public void setWebHooksService(IWebHooksService webHooksService) {
        this.webHooksService = webHooksService;
    }

    public void setSysLogInmsgService(ISysLogInmsgService sysLogInmsgService) {
        this.sysLogInmsgService = sysLogInmsgService;
    }

    public void setSysRoleService(ISysRoleService sysRoleService) {
        this.sysRoleService = sysRoleService;
    }



    public String testAddUser() {
        User userBefore =  null;
        User userAfter =  new User();
        userAfter.setLOGIN_ID("testifuser");
        userAfter.setNAME("测试接口用户");
        userAfter.setDEPT_ID("10");
        userAfter.setEMAIL_ADDR("test@123.com");
        userAfter.setLOCAL_PHONE("12345678");
        userAfter.setLOGIN_PHONE("12345678901");
        userAfter.setCREATED_BY(this.getCurrentUser().getLOGIN_ID());
        userAfter.setCREATED_AT(EventProcessorUtil.getNowTime());
        String object_id = userAfter.getLOGIN_ID();
        String object_kind = "user";
        String operate_kind = "create";
        try {
            HookRequestBody hrb = new HookRequestBody();
            hrb.setObject_kind(object_kind);
            hrb.setOperate_kind(operate_kind);
            hrb.setObject_before(EventProcessorUtil.toJSONWithOutNull(userBefore));
            hrb.setObject_after(EventProcessorUtil.toJSONWithOutNull(userAfter));
            hrb.setObject_id(object_id);
            PostMethod post = new PostMethod(testUrl);
            post.setRequestBody(JSONUtil.toJSON(hrb));
            try {
                new HttpClient().executeMethod(post);
            }catch (Exception e){
                logger.error(e);
                tip = "测试增加用户同步接口:接口连接失败";
            }
            tip = "测试增加用户同步接口:"+testUrl+"  status:"+post.getStatusCode()+"  return:"+post.getResponseBodyAsString();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return SUCCESS;
    }

    public String getTip() {
        return tip;
    }

    public void setTip(String tip) {
        this.tip = tip;
    }

    public String getTestUrl() {
        return testUrl;
    }

    public void setTestUrl(String testUrl) {
        this.testUrl = testUrl;
    }
}
